<template>
  <div>
    <div class="user-input cla">
      <div class="all-input">
        <div class="input-name">
          <span>登录账号</span>
          <el-input
            v-model.trim="queryInfo.userName"
            placeholder="请输入登录账号"
            maxlength="10"
            class="mr-10"
            clearable
          />
        </div>
        <div class="input-name">
          <span>手机号</span>
          <el-input
            v-model.trim="queryInfo.phone"
            placeholder="请输入手机号"
            class="mr-10"
            clearable
          />
        </div>
        <div class="input-name">
          <span>角色</span>
          <el-select
            v-model="queryInfo.roleId"
            filterable
            clearable
            placeholder="请选择角色"
            class="mr-10"
          >
            <el-option
              :label="role.label"
              :value="role.value"
              v-for="role in roles"
              :key="role.value"
            />
          </el-select>
        </div>
      </div>

      <div class="btn">
        <el-button class="el-icon-refresh" @click="resetUserList"
          >重置</el-button
        >
        <el-button class="el-icon-search" @click="queryConditionUserList"
          >查询</el-button
        >
      </div>
    </div>
    <div class="main">
      <div class="mb-10 addBox">
        <el-button @click="handleAddUser">
          <i class="el-icon-document-add"></i>新增
        </el-button>
      </div>
      <el-table
        v-loading="listLoading"
        :data="tableData"
        border
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
      >
        <el-table-column label="序号" type="index" width="60" />
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button type="text" @click="handleModify(scope)">
              修改
            </el-button>
            <el-button type="text" @click="handleResetPassword(scope)">
              重置密码
            </el-button>
            <el-button
              :loading="scope.row.optLoading"
              type="text"
              @click="handleOpt(scope)"
            >
              {{ scope.row.status == 10 ? "禁用" : "启用" }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="userName"
          :show-overflow-tooltip="true"
          label="登录账号"
          min-width="110"
        />
        <el-table-column
          prop="nickName"
          :show-overflow-tooltip="true"
          label="用户名称"
          min-width="110"
        />
        <el-table-column
          prop="phone"
          :show-overflow-tooltip="true"
          label="手机号"
          min-width="125"
        />
        <el-table-column
          prop="roleId"
          :show-overflow-tooltip="true"
          label="角色"
          min-width="130"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.roleId == 1" type="success">管理员</el-tag>
            <el-tag v-if="scope.row.roleId == 2" type="primary">
              普通用户
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          :show-overflow-tooltip="true"
          label="状态"
          min-width="80"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status == 10" type="success">启用</el-tag>
            <el-tag v-if="scope.row.status == 20" type="danger">禁用</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        v-show="totalNum > 0"
        background
        :current-page="params.page"
        :page-sizes="[10, 30, 50, 100]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalNum"
        style="display: flex; justify-content: center; margin-top: 10px"
        :disabled="totalNum <= 10 ? true : false"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增编辑框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
      width="560px"
    >
      <el-form
        ref="ruleForm"
        :model="form"
        status-icon
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="登录账号" prop="userName">
          <el-input
            v-model.trim="form.userName"
            maxlength="10"
            autocomplete="off"
            placeholder="请输入登录账号"
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item label="用户名称" prop="nickName">
          <el-input
            v-model.trim="form.nickName"
            maxlength="10"
            autocomplete="off"
            placeholder="请输入用户名称"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model.trim="form.phone"
            maxlength="11"
            placeholder="请输入手机号"
          />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select
            v-model.trim="form.roleId"
            filterable
            placeholder="请选择角色"
            value-key="value"
            style="width: 100%"
          >
            <el-option
              :label="role.label"
              :value="role.value"
              v-for="role in roles"
              :key="role.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <div class="dialog-footer">
            <el-button type="" @click="handleCancel">取消</el-button>
            <el-button
              :loading="addLoading"
              type="primary"
              @click="handleConfirm('ruleForm')"
              >确认</el-button
            >
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 删除框 -->
    <el-dialog
      title="删除"
      :visible.sync="dialogDelete"
      width="480px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="dialog-delete-content">
        <p>是否确认删除?</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="" @click="dialogDelete = false">取 消</el-button>
        <!-- <el-button type="primary" @click="confirmDeletion">确认</el-button> -->
      </div>
    </el-dialog>

    <!-- 重置密码 -->
    <el-dialog
      title="重置密码"
      :visible.sync="dialogPassword"
      width="480px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="dialog-delete-content">
        <p>是否确认重置密码？</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="" @click="dialogPassword = false">取 消</el-button>
        <el-button type="primary" @click="confirmResetPass">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import {
  queryUserList,
  resetPassword,
  addUserItem,
  editUserItem,
  optUserItem,
} from "@/api/user";
import { roles } from "@/constant";
import defaultSettings from "@/settings";
const DIALOG_TITLE_ADD_USER = "新增用户";
const DIALOG_TITLE_MODIFY_USER = "修改用户";

export default {
  name: "UserList",
  computed: {
    ...mapGetters(["dictsMap"]),
  },
  data() {
    // 表单用户名校验
    const userNameValidate = (rule, value, callback) => {
      if (!this.pattern.test(value)) {
        callback("请填写5~10位字符,不包括中文");
      }
      if (value === "" || typeof value === "undefined") {
        callback("请输入用户名");
      }
      callback();
    };

    // 表单登录账号校验
    const accountValidate = async (rule, value, callback) => {
      if (!this.jobPattern.test(value)) {
        callback("请填写5~20位英文+数字的有效工号");
      }
      if (value === "" || typeof value === "undefined") {
        callback("请输入手机号");
      }
      callback();
    };

    // 表单邮件校验
    const emailValidate = (rule, value, callback) => {
      if (value === "" || typeof value === "undefined") {
        callback("请输入邮箱");
      }
      if (!this.emailPattern.test(value)) {
        callback("输入的邮箱号不符合规范，请重新输入");
      }
      callback();
    };
    return {
      roles,
      data: defaultSettings.allPermission,
      listLoading: false,
      queryInfo: {
        userName: "",
        phone: "",
        roleId: "",
        page: 1,
        pageSize: 10,
      },
      params: {
        page: 1, // 当前页数
        pageSize: 10, // 默认每页显示10条
      },
      totalNum: 1, // 总页数,
      tableData: [],
      dialogVisible: false,
      dialogTitle: "",
      isEdit: null,
      editInfo: {},
      form: {
        userName: "",
        nickName: "",
        phone: "",
        roleId: "",
      },
      // pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/,
      pattern: /^(?!.*[\u4E00-\u9FA5]).+$/, //字符串中不包含任何中文字符
      jobPattern: /^[A-Za-z0-9]+$/,
      emailPattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
      rules: {
        userName: [
          { required: true, message: "请输入登录账号", trigger: "blur" },
          {
            min: 5,
            max: 10,
            message: "长度在 5 到 10 个字符",
            trigger: "blur",
          },
          { required: true, validator: userNameValidate, trigger: "blur" },
        ],
        nickName: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
          // { required: true, validator: userNameValidate, trigger: "blur" },
        ],
        phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
        roleId: [{ required: true, message: "请选择角色", trigger: "change" }],
      },
      addLoading: false,
      dialogDelete: false,
      dialogPassword: false,
    };
  },
  created() {
    this.initialization();
  },
  methods: {
    // 确定重置密码
    confirmResetPass() {
      const { id } = this.editInfo;
      resetPassword({
        userId: id,
      }).then((res) => {
        if (res.result == 0) {
          this.$message({
            message: "重置成功",
            type: "success",
          });
        }
      });
      this.dialogPassword = false;
      this.initialization();
    },
    // 点击重置密码
    handleResetPassword(scope) {
      this.dialogPassword = true;
      this.editInfo = scope.row;
    },
    async handleOpt(scope) {
      const { id, status } = scope.row;
      const par = {
        ids: [id],
        optType: status == 10 ? 20 : 10,
      };
      scope.row.optLoading = true;
      try {
        await optUserItem(par);
        this.$message.success("禁用成功");
        this.initialization();
      } catch (error) {
        scope.row.optLoading = false;
      } finally {
        scope.row.optLoading = false;
      }
    },
    // 编辑信息
    handleModify(scope) {
      this.dialogVisible = true;
      this.dialogTitle = DIALOG_TITLE_MODIFY_USER;
      this.isEdit = true;
      const { userName, nickName, phone, roleId } = scope.row;
      this.form = {
        userName,
        nickName,
        phone,
        roleId,
      };
      this.editInfo = scope.row;
    },

    // 确认添加或编辑
    handleConfirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addLoading = true;
          let param = { ...this.form };
          if (this.isEdit) {
            const { id } = this.editInfo;
            param = { id, ...this.form };
          }
          const api = this.isEdit ? editUserItem : addUserItem;
          api(param)
            .then((res) => {
              if (res.result == 0) {
                this.initialization();
                this.dialogVisible = false;
                this.$message({
                  message: this.isEdit ? "编辑成功" : "添加成功",
                  type: "success",
                });
              } else {
                this.$message({
                  message: res.msg,
                  type: "error",
                });
              }
            })
            .finally(() => {
              this.addLoading = false;
            });
        } else {
          return false;
        }
      });
    },
    handleCancel() {
      this.dialogVisible = false;
    },
    // 点击添加
    handleAddUser() {
      this.dialogVisible = true;
      this.dialogTitle = DIALOG_TITLE_ADD_USER;
      this.isEdit = false;
      for (const key in this.form) {
        if (typeof this.form[key] === "object") {
          this.form[key] = [];
        } else {
          this.form[key] = "";
        }
      }
      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate();
      });
    },
    // 点击查询
    queryConditionUserList() {
      this.params = {
        ...this.params,
        ...this.queryInfo,
        page: 1,
      };
      this.initialization();
    },
    // 重置
    resetUserList() {
      for (const key in this.queryInfo) {
        if (typeof this.queryInfo[key] === "object") {
          this.queryInfo[key] = [];
        } else {
          this.queryInfo[key] = undefined;
        }
      }
      this.queryInfo.page = 1;
      this.queryInfo.pageSize = 10;
    },

    // 切换页数
    handleCurrentChange(val) {
      this.params = this.queryInfo;
      this.params.page = val;
      this.initialization();
    },
    // 切换页面显示个数
    handleSizeChange(val) {
      this.params = this.queryInfo;
      this.params.pageSize = val;
      this.initialization();
    },
    // 初始化
    initialization() {
      this.listLoading = true;
      queryUserList(this.params)
        .then((res) => {
          this.totalNum = res.data.total;
          this.tableData = res.data.records.map((item) => {
            item.optLoading = false;
            return item;
          });
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
  },
};
</script>
<style lang="scss" scoped>
.user-type {
  display: flex;
  width: 100%;
  overflow-y: hidden;
  span {
    width: 80px;
    display: inline-block;
    position: relative;
    font-size: 20px;
    cursor: pointer;
    text-align: center;
    white-space: nowrap;
    margin-right: 20px;
    font-size: 14px;
    color: #666666;
  }
  .active {
    color: #2878ff;
    &:after {
      content: "";
      width: 64px;
      position: absolute;
      bottom: 8px;
      left: 7px;
      height: 8px;
      background-color: #d0e2ff;
      border-radius: 6px;
      opacity: 0.5;
    }
  }
  > span {
    margin-right: 10px;
  }
}
.user-input {
  border-radius: 10px;
  background: #fff;
  box-shadow: 0px 0px 14px 0px rgba(0, 0, 0, 0.1);
  padding: 30px 0 80px;
  position: relative;
}
.dialog-delete-content {
  font-size: 20px;
  text-align: center;
}
.select-organization {
  -webkit-appearance: none;
  background-color: #fff;
  background-image: none;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  box-sizing: border-box;
  color: #606266;
  display: inline-block;
  font-size: inherit;
  height: 32px;
  line-height: 32px;
  outline: 0;
  padding: 0 15px;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  padding-right: 30px;
  width: 100%;
  cursor: pointer;
  position: relative;
}
.select-organization > div {
  width: 100%;
  position: absolute;
  margin-top: 20px;
  z-index: 10000;
  top: 18px;
  left: 0;
}
.organization {
  width: 200px;
  display: inline-block;
  position: relative;
}
.organization-sp {
  font-size: 14px;
  color: rgb(192, 196, 204);
  z-index: -1;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
::v-deep .el-dialog {
  width: 35%;
}
::v-deep .el-icon-arrow-down::before {
  position: absolute;
  right: 6px;
  top: 5px;
  color: rgb(192, 196, 204);
}
::v-deep .el-table__header tr,
::v-deep .el-table__header th {
  padding: 0;
  height: 48px;
}
::v-deep .el-table__body tr,
::v-deep .el-table__body td {
  padding: 0;
  height: 48px;
}
::v-deep .el-scrollbar__bar {
  height: 6px;
  background: rgb(242, 242, 242);
  margin-top: 5px;
}
.tree {
  overflow-y: scroll;
  overflow-x: scroll;
  width: 100%;
  height: 700px;
  overflow: auto;
}
.el-tree {
  min-width: 100%;
  display: inline-block !important;
}
::v-deep .el-select-group__title {
  font-size: 20px;
  font-weight: bold;
}
.input-name {
  margin: 8px 0;
  align-items: center;
  display: flex;
  width: 25%;
  .el-select {
    width: 100%;
  }
}
.input-name > span {
  width: 80px;
  height: 20px;
  opacity: 1;
  font-size: 14px;
  font-family: PingFangSC, PingFangSC-Regular;
  font-weight: 400;
  text-align: right;
  color: #666;
  line-height: 20px;
  letter-spacing: 0px;
  margin-right: 10px;
  display: inline-block;
  white-space: nowrap;
}
.btn {
  height: 32px;
  position: absolute;
  right: 51px;
  bottom: 30px;
}
.btn > :first-child {
  width: 100px;
  height: 32px;
  opacity: 1;
  border: 1px solid #dddddd;
  border-radius: 21px;
  color: #333333;
  margin-left: 24px;
  padding: 0;
  font-size: 12px;
}
.btn > :last-child {
  width: 100px;
  height: 32px;
  opacity: 1;
  background: #307eff;
  border-radius: 20px;
  color: #fff;
  margin-left: 20px;
  margin-bottom: 16px;
  padding: 0;
  font-size: 12px;
}
.el-select {
  width: 200px;
}
.main {
  border-radius: 10px;
  background: #fff;
  margin-top: 15px;
  padding: 14px 20px;
}
::v-deep .el-table--striped .el-table__body tr.el-table__row--striped td {
  background: #f8f8f8;
}
.addBox {
  padding-bottom: 5px;
  position: relative;
}
.addBox > .el-button {
  width: 100px;
  height: 32px;
  opacity: 1;
  border: 1px solid #307eff;
  border-radius: 5px;
  color: #307eff;
  padding: 0;
  font-size: 12px;
}
.el-icon-document-add {
  margin-right: 5px;
}
::v-deep .warning-row {
  background: rgb(248, 248, 248);
}
::v-deep .el-dialog {
  border-radius: 8px;
}
::v-deep .el-dialog__header {
  margin: 0 21px 0 36px;
  border-bottom: 1px solid #e9e9e9;
  text-align: left;
  padding: 20px 0;
}
::v-deep .el-dialog__title {
  font-size: 18px;
  line-height: 22px;
  color: #303133;
  font-family: PingFangSC, PingFangSC-Medium;
}
::v-deep .el-form-item__label {
  width: 120px;
  height: 20px;
  opacity: 1;
  font-size: 14px;
  font-family: PingFangSC, PingFangSC-Regular;
  font-weight: 400;
  text-align: right;
  color: #333333;
  font-weight: 500;
}
::v-deep .el-form {
  padding-left: 30px;
  padding-right: 90px;
}
.dialog-footer {
  text-align: center;
}
.dialog-footer > :last-child {
  width: 88px;
  height: 40px;
  opacity: 1;
  border-radius: 5px;
}
.dialog-footer > :first-child {
  width: 88px;
  height: 40px;
  opacity: 1;
  border: 1px solid #307eff;
  border-radius: 5px;
  color: #307eff;
  font-size: 14px;
}
::v-deep .el-input.is-disabled .el-input__inner {
  border: none;
  background: #fff;
  color: #606266;
}
.cla::after {
  content: "";
  height: 0;
  display: block;
  clear: both;
}
.el-icon-refresh:before {
  margin-right: 5px;
}
.el-icon-search:before {
  margin-right: 5px;
}

/* 展开按钮样式 */
.open_close {
  position: absolute;
  bottom: -10px;
  width: 50px;
  height: 50px;
  text-align: center;
  border-radius: 50%;
  left: 50%;
  transform: translateX(-50%);
  background-color: #fff;
  line-height: 80px;
  cursor: pointer;
}
::v-deep .open_close .el-icon-arrow-down::before {
  right: 16px;
  top: 36px;
}
::v-deep .el-input__inner {
  width: 100%;
}
.all-input {
  padding: 0 20px;
  display: flex;
  width: 100%;
  flex-wrap: wrap;
}
::v-deep .input-name .el-input__inner {
  height: 32px;
}
::v-deep .el-input__icon {
  line-height: 32px;
}
::v-deep .el-textarea__inner {
  padding-right: 36px;
}
.tree-div {
  width: 100%;
  min-height: 100px;
  max-height: 400px;
  overflow-y: auto;
  position: absolute;
  z-index: 10000;
}
::v-deep .el-input__suffix {
  right: 15px;
}
::v-deep .el-scrollbar__wrap {
  margin-right: -7px !important;
}
.dialog-tree {
  position: relative;
}
.position-tree {
  max-height: 300px;
  overflow-y: auto;
  position: absolute;
  width: 100%;
  z-index: 10000;
}
.inp-btn {
  position: absolute;
  display: block;
  left: 6px;
  top: 6px;
  background-color: #f4f4f5;
  border-color: #e9e9eb;
  color: #909399;
  box-sizing: border-box;
  margin: 2px 0 2px 6px;
  height: 24px;
  padding: 0 8px;
  line-height: 22px;
  border-width: 1px;
  border-style: solid;
  border-radius: 4px;
  white-space: nowrap;
  font-size: 12px;
}
.el-icon-close {
  transform: scale(0.8);
  border-radius: 50%;
  text-align: center;
  position: relative;
  cursor: pointer;
  font-size: 12px;
  height: 16px;
  width: 16px;
  line-height: 16px;
  vertical-align: middle;
  color: #909399;
  background-color: #c0c4cc;
  right: -7px;
  top: -1px;
}
::v-deep .el-table__body {
  width: 100%;
  table-layout: fixed !important;
}
</style>
